package com.google.code.sms.android.util;

import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;

/**
 * @author Sindre Mehus
 * @version $Id$
 */
public class TimeLimitedCache<T> {

    private SoftReference<T> value;
    private final long ttlMillis;
    private long expires;

    public TimeLimitedCache(long ttl, TimeUnit timeUnit) {
        this.ttlMillis = TimeUnit.MILLISECONDS.convert(ttl, timeUnit);
    }

    public T get() {
        return System.currentTimeMillis() < expires ? value.get() : null;
    }

    public void set(T value) {
        set(value, ttlMillis, TimeUnit.MILLISECONDS);
    }

    public void set(T value, long ttl, TimeUnit timeUnit) {
        this.value = new SoftReference<T>(value);
        expires = System.currentTimeMillis() + timeUnit.toMillis(ttl);
    }

    public void clear() {
        expires = 0L;
        value = null;
    }
}
